import smtplib
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.utils import parseaddr, formataddr
import smtplib


def format_addr(s):
    name, addr = parseaddr(s)
    result = formataddr((Header(name, 'utf-8').encode(), addr))
    return result


def connect_to_server():
    smtp_server = 'smtp-mail.outlook.com'
    port = 587
    sender_email = 'qy_service@outlook.com'
    password = 'MESSAGEqwe123'

    server = smtplib.SMTP(smtp_server, port)
    server.ehlo()
    server.starttls()
    server.ehlo()
    server.login(sender_email, password)

    return server


def send_email():
    from_addr = 'qy_service@outlook.com'
    to_addr = 'yshjbw@163.com'
    msg = MIMEMultipart()
    content = MIMEText('测试邮件', 'plain', 'utf-8')
    msg.attach(content)
    # FIXME: 此处的邮箱地址无法拼接到from和to
    msg['From'] = format_addr('来自<%s>' % from_addr)
    msg['To'] = format_addr('管理员<%s>' % to_addr)
    msg['Subject'] = Header('标题', 'utf-8').encode()
    print(msg)
    server = connect_to_server()
    server.sendmail(from_addr, [to_addr], msg.as_string())
    server.quit()
